<template>
  <div class="page-wapper">
    <!-- 发送日报 -->
    <el-row :gutter="20">
      <!-- 左边部分 -->
      <el-col :xs="24" :span="12" :class="{ mb_s: isPhone }">
        <!-- <div class="date_title mb_s">{{ todayDateTime }}</div> -->
        <div class="show_box">
          <!-- changeReportData 事件名不能改成 change,莫名的bug -->
          <ReportCommitList
            ref="reportCommitListRef"
            :lastFinishReportList="reportCommitData.lastFinishReportList"
            :todayPlanReportList="reportCommitData.todayPlanReportList"
            :reportCommitRemark="reportCommitData.reportCommitRemark"
            :reasonVisible="false"
            :deleteBtnVisible="true"
            :createBtnVisible="true"
            @changeReportData="changeReportData"
          />
        </div>
        <div class="btns_box pt_s">
          <el-button
            v-if="userInfo.isLeader"
            :loading="getMemberReportLoading"
            type="warning"
            size="mini"
            @click="getMemberReportDataConfirm"
          >
            获取组员提交的日报
          </el-button>
          <el-button
            :loading="showBoxLoading"
            size="mini"
            type="primary"
            @click="onResetMethod"
          >
            重新获取
          </el-button>
        </div>
      </el-col>

      <!-- 右边部分 -->
      <el-col :xs="24" :span="12" v-loading="showBoxLoading">
        <div class="report_cell_title">上个工作日问题反馈</div>
        <div class="pt_s f_1">
          <!-- .trim属性会使最下排文字不能换行 -->
          <el-input
            v-model="reportCommitData.reportCommitRemark"
            placeholder="填写是否有项目延误、项目问题等情况..."
            type="textarea"
            resize="none"
            autofocus
            clearable
            maxlength="2000"
            show-word-limit
          ></el-input>
        </div>
        <div class="btns_box pt_s">
          <el-button
            type="primary"
            size="mini"
            :loading="addBtnLoading"
            @click="onSendMethod"
          >
            发送
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { reactive, ref, getCurrentInstance, computed, onActivated } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { unionBy, cloneDeep } from "lodash";
import ReportCommitList from "./components/ReportCommitList.vue";

const initReportCommitData = () => {
  return {
    id: null,
    lastFinishReportList: [],
    todayPlanReportList: [],
    reportCommitRemark: "",
  };
};

export default {
  name: "reportCommitForm",
  components: { ReportCommitList },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $moment = proxy.$moment;
    const router = useRouter();
    const route = useRoute();
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);
    const isPhone = computed(() => store.state.isPhone);

    const addBtnLoading = ref(false);
    const showBoxLoading = ref(false);

    const reportCommitListRef = ref(null);

    const todayDateTime = ref("");

    const reportCommitData = reactive(initReportCommitData());

    // 发送
    const onSendMethod = () => {
      addBtnLoading.value = true;
      if (!reportCommitListRef.value) {
        addBtnLoading.value = false;
        return;
      }
      const reportData = reportCommitListRef.value.reportData;
      $api.reportCommit
        .saveOrUpdate({
          reportCommitRemark: reportCommitData.reportCommitRemark,
          ...reportData,
        })
        .then((res) => {
          addBtnLoading.value = false;
          ElMessage.success("发送成功！");
          router.push({
            name: "SendedReportManage",
          });
          store.commit("delTagsByName", { name: route.name });
        })
        .catch((err) => {
          addBtnLoading.value = false;
          console.error("onSendMethod error: ", err);
        });
    };

    // 发送
    // const onSendMethod = () => {
    //   addBtnLoading.value = true;
    //   if (!reportCommitListRef.value) {
    //     return;
    //   }
    //   const lastFinishReportIds =
    //     reportCommitListRef.value.reportData.lastFinishReportList.map(
    //       (item) => item.id
    //     );
    //   const todayPlanReportIds =
    //     reportCommitListRef.value.reportData.todayPlanReportList.map(
    //       (item) => item.id
    //     );
    //   $api.reportCommit
    //     .sendTodayReport({
    //       lastFinishReportIds,
    //       todayPlanReportIds,
    //       reportCommitRemark: reportCommitData.reportCommitRemark,
    //     })
    //     .then((res) => {
    //       addBtnLoading.value = false;
    //       ElMessage.success("发送成功！");
    //       router.push({
    //         name: "SendedReportManage",
    //       });
    //       store.commit("delTagsByName", { name: route.name });
    //     })
    //     .catch((err) => {
    //       addBtnLoading.value = false;
    //       console.error("onSendMethod error: ", err);
    //     });
    // };

    // 重置
    const onResetMethod = () => {
      initPageData();
    };

    // 获取当前用户的今天添加的日程数据
    const getMyToDayReportList = () => {
      const startDateTime = $moment()
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      const endDateTime = $moment().endOf("day").format("YYYY-MM-DD HH:mm:ss");
      return $api.report.getToDayReportList({
        current: 1,
        size: 999,
        startDateTime,
        endDateTime,
      });
    };

    // 获取登录用户的上个工作日的日报列表
    const getMyLastFinishReportList = () => {
      return $api.report.lastWorkDayReportSelf();
    };

    const getMemberReportLoading = ref(false);

    const getMemberReportDataConfirm = () => {
      ElMessageBox.confirm(
        "此操作会覆盖已编辑的组员日报，确定要继续吗？",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          getMemberReportData();
        })
        .catch(() => {});
    };

    // 获取组员日报提交数据
    const getMemberReportData = () => {
      const startCreatedTime = $moment()
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      const endCreatedTime = $moment()
        .endOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      getMemberReportLoading.value = true;
      $api.group
        .memberReport({
          startCreatedTime,
          endCreatedTime,
        })
        .then((res) => {
          let reportCommitRemark = "";
          let lastFinishReportList = reportCommitData.lastFinishReportList;
          let todayPlanReportList = reportCommitData.todayPlanReportList;
          res.data[0].userReportCommitList.forEach((item) => {
            if (item.reportCommitList.length) {
              lastFinishReportList = lastFinishReportList.concat(
                item.reportCommitList[0].lastFinishReportList
              );
              todayPlanReportList = todayPlanReportList.concat(
                item.reportCommitList[0].todayPlanReportList
              );
              reportCommitRemark += item.reportCommitList[0].reportCommitRemark;
            }
          });
          const hasNotIdLastFinishReportList = [];
          // 有 id 的需要去重
          const hasIdLastFinishReportList = [];
          lastFinishReportList.forEach((item) => {
            if (item.id) {
              hasIdLastFinishReportList.push(item);
            } else {
              hasNotIdLastFinishReportList.push(item);
            }
          });
          const unionLastFinishReportList = unionBy(
            hasIdLastFinishReportList,
            "id"
          );
          reportCommitData.lastFinishReportList =
            hasNotIdLastFinishReportList.concat(unionLastFinishReportList);

          const hasNotIdTodayPlanReportList = [];
          // 有 id 的需要去重
          const hasIdTodayPlanReportList = [];
          todayPlanReportList.forEach((item) => {
            if (item.id) {
              hasIdTodayPlanReportList.push(item);
            } else {
              hasNotIdTodayPlanReportList.push(item);
            }
          });
          const unionTodayPlanReportList = unionBy(
            hasIdTodayPlanReportList,
            "id"
          );
          reportCommitData.todayPlanReportList =
            hasNotIdTodayPlanReportList.concat(unionTodayPlanReportList);

          reportCommitData.reportCommitRemark = reportCommitRemark;
        })
        .catch((err) => {
          console.error("getMemberReportData error: ", err);
        })
        .finally(() => {
          getMemberReportLoading.value = false;
        });
    };

    const changeReportData = ({
      lastFinishReportList,
      todayPlanReportList,
    }) => {
      reportCommitData.lastFinishReportList = lastFinishReportList;
      reportCommitData.todayPlanReportList = todayPlanReportList;
    };

    const initPageData = () => {
      showBoxLoading.value = true;
      // if (userInfo.value.isLeader) {
      // Promise.all([
      //   getMyLastFinishReportList(),
      //   getMyToDayReportList(),
      //   getMemberReportData(),
      // ])
      //   .then((res) => {
      //     showBoxLoading.value = false;
      //     let reportCommitRemark = "";
      //     let lastFinishReportList = [];
      //     let todayPlanReportList = [];
      //     lastFinishReportList = lastFinishReportList.concat(res[0].data);
      //     todayPlanReportList = todayPlanReportList.concat(res[1].data.list);
      //     res[2].data[0].userReportCommitList.forEach((item) => {
      //       if (item.reportCommitList.length) {
      //         lastFinishReportList = lastFinishReportList.concat(
      //           item.reportCommitList[0].lastFinishReportList
      //         );
      //         todayPlanReportList = todayPlanReportList.concat(
      //           item.reportCommitList[0].todayPlanReportList
      //         );
      //         reportCommitRemark +=
      //           item.reportCommitList[0].reportCommitRemark;
      //       }
      //     });
      //     reportCommitData.lastFinishReportList = lastFinishReportList;
      //     reportCommitData.todayPlanReportList = todayPlanReportList;
      //     reportCommitData.reportCommitRemark = reportCommitRemark;
      //   })
      //   .catch((err) => {
      //     console.error("Promise.all error: ", err);
      //     showBoxLoading.value = false;
      //   });
      // } else {
      Promise.all([getMyLastFinishReportList(), getMyToDayReportList()])
        .then((res) => {
          showBoxLoading.value = false;
          let lastFinishReportList = [];
          let todayPlanReportList = [];
          lastFinishReportList = lastFinishReportList.concat(res[0].data);
          todayPlanReportList = todayPlanReportList.concat(res[1].data.list);
          reportCommitData.lastFinishReportList = lastFinishReportList;
          reportCommitData.todayPlanReportList = todayPlanReportList;
        })
        .catch((err) => {
          console.error("Promise.all error: ", err);
          showBoxLoading.value = false;
        });
      // }
    };

    /**
     * 初始化调用
     */
    // initPageData();

    // onMounted(() => {
    // todayDateTime.value = $moment().format("YYYY-MM-DD");
    // });

    onActivated(() => {
      if (route.params.refresh) {
        initPageData();
      }
    });

    return {
      userInfo,
      isPhone,
      addBtnLoading,
      reportCommitListRef,
      showBoxLoading,
      todayDateTime,
      onSendMethod,
      onResetMethod,
      reportCommitData,
      getMemberReportDataConfirm,
      getMemberReportLoading,
      changeReportData,
    };
  },
};
</script>
<style lang="less" scoped>
.btns_box {
  text-align: center;
}

.container.mobile {
  display: block;
}

.left_content {
  width: 50%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.right_content {
  flex: 1;
  height: 100%;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  border-left: 2px dashed #dcdfe6;
  :deep(.el-textarea) {
    height: 100%;
  }
  :deep(.el-textarea__inner) {
    height: 100%;
  }
}

.show_box {
  flex: 1;
  overflow: hidden auto;
}

.date_title {
  font-size: 18px;
  line-height: 22px;
}

.report_cell_title {
  font-size: 16px;
  padding: 10px 20px;
  // background-image: linear-gradient(to right top, #ec008c, #6739b6);
  background-color: #faecd8;
  // background-color: #f2f6fc;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .time_text {
    font-size: 14px;
    font-weight: 400;
    color: #999;
  }
}
</style>
